import { matchModifier } from 'az-keyboard-modifier'
import { toKeyCode } from './utils'

export function dispatchKeyEvent(type, key = 0, { el = document, modifiers = '' } = {}) {
  const keyCode = toKeyCode(key)
  modifiers = matchModifier(modifiers)

  let event

  if (document.createEvent) {
    // createEvent for Firefox and Chrome
    const keyboardEventInitOptions = {
      keyCode,
      which: keyCode,
      bubbles: true,
      cancelable: true,
    }
    for (let modifier in modifiers) keyboardEventInitOptions[modifier + 'Key'] = modifiers[modifier]

    event = new KeyboardEvent(type, keyboardEventInitOptions)

    el.dispatchEvent(event)
  } else if (document.createEventObject) {
    // createEventObject for IE
    event = document.createEventObject()

    event.keyCode = keyCode
    event.which = keyCode
    for (let modifier in modifiers) event[modifier + 'Key'] = modifiers[modifier]

    el.fireEvent('on' + type, event)
  }
}
